using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NLog;

namespace LDNS.Models
{
    /// <summary>
    /// 泛域名DNS记录模型
    /// 作者：huobing
    /// </summary>
    public class DnsRecordConfig
    {
        /// <summary>
        /// IP地址
        /// </summary>
        public string IP { get; set; } = string.Empty;
        
        /// <summary>
        /// 域名模式（支持通配符*）
        /// </summary>
        public string DomainPattern { get; set; } = string.Empty;
        
        /// <summary>
        /// 记录类型（A、PTR等）
        /// </summary>
        public string RecordType { get; set; } = "A";
        
        /// <summary>
        /// 生存时间（秒）
        /// </summary>
        public int Ttl { get; set; } = 3600;
        
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;
        
        /// <summary>
        /// 更新时间
        /// </summary>
        public DateTime UpdatedTime { get; set; } = DateTime.Now;
        
        /// <summary>
        /// 检查域名是否匹配模式
        /// </summary>
        /// <param name="domain">要检查的域名</param>
        /// <returns>是否匹配</returns>
        public bool IsMatch(string domain)
        {
            if (string.IsNullOrEmpty(domain) || string.IsNullOrEmpty(DomainPattern))
                return false;
                
            // 将通配符模式转换为正则表达式
            string pattern = DomainPattern
                .Replace(".", "\\.")
                .Replace("*", ".*");
                
            return Regex.IsMatch(domain, "^" + pattern + "$", RegexOptions.IgnoreCase);
        }
        
        /// <summary>
        /// 获取匹配优先级（更精确的匹配优先级更高）
        /// </summary>
        /// <param name="domain">域名</param>
        /// <returns>优先级值（越小优先级越高）</returns>
        public int GetMatchPriority(string domain)
        {
            if (!IsMatch(domain))
                return int.MaxValue;
                
            // 通配符数量越少，优先级越高
            int wildcardCount = DomainPattern.Count(c => c == '*');
            
            // 模式长度越长，优先级越高
            int patternLength = DomainPattern.Length;
            
            return wildcardCount * 1000 + (100 - patternLength);
        }
    }
}